package com.sc.auction.pay.Service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.auction.common.exception.AuctionException;
import com.sc.auction.common.pojo.User;
import com.sc.auction.common.util.R;
import com.sc.auction.pay.Config.AlipayConfig;
import com.sc.auction.pay.Service.AlipayService;
import com.sc.auction.pay.feign.UserFeignService;
import com.sc.auction.pay.pojo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


@Service
@Transactional
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private com.sc.auction.pay.Service.OrdersService ordersService;

    /** 调取支付宝接口 web端支付*/
    DefaultAlipayClient alipayClient = new DefaultAlipayClient(
            AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key,
            "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);


    @Override
    public String webPagePay(String outTradeNo, Integer totalAmount, String subject,String returnUrl) throws Exception {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        /** 同步通知，支付完成后，支付成功页面*/
        alipayRequest.setReturnUrl(returnUrl);
        /** 异步通知，支付完成后，需要进行的异步处理*/
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
                + "\"total_amount\":\""+ totalAmount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\"商品名称\","
                + "\"timeout_express\":\"90m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        /**转换格式*/
        String result = alipayClient.pageExecute(alipayRequest).getBody().replace('\"','\'');
        return result;
    }


    //用户调用账户余额付款
    @Override
    public R balancePay(Integer id,BigDecimal totalAmount,Integer orderId) throws AuctionException {
        R  r = userFeignService.getUserById(id);
        Object user1 = r.getData().get("user");
        User user = JSON.toJavaObject((JSONObject)user1,User.class);
        int flag = user.getBalance().compareTo(totalAmount);
        if(flag == -1){
            return R.error().code(201).message("账户余额不足");
        }else{
            user.setBalance(user.getBalance().subtract(totalAmount));
            R r1 = userFeignService.update(user);
            if(r1.getCode()==200){
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("id",orderId);
                Orders orders = new Orders();
                orders.setStatus(2);
                ordersService.update(orders,queryWrapper);
                return R.ok().code(200).message("支付成功");
            }else{
                return R.error().code(301).message("服务器连接出现了异常");
            }
        }
    }
}
